// stores/classifyLov.ts
import { defineStore } from "pinia";
import { classifyLov } from "@/api/ruleBase";

// 定义 localStorage 的 key
const STORAGE_KEY = "classify-lov-store";

export const useClassifyLovStore = defineStore("Lov", {
  state: () => ({
    classifyLov: {} as Record<string, any>,
    expirationTime: 0 as number,
  }),

  actions: {
    // 从 localStorage 加载数据
    loadFromStorage() {
      const storedData = localStorage.getItem(STORAGE_KEY);
      if (storedData) {
        const { classifyLov, expirationTime } = JSON.parse(storedData);
        this.classifyLov = classifyLov;
        this.expirationTime = expirationTime;
      }
    },

    // 保存数据到 localStorage
    saveToStorage() {
      const data = {
        classifyLov: this.classifyLov,
        expirationTime: this.expirationTime,
      };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    },

    // 获取分类数据（带缓存逻辑）
    async fetchClassifyLov() {
      // 如果数据未过期，直接返回缓存
      if (this.expirationTime && this.expirationTime > Date.now()) {
        return this.classifyLov;
      }

      try {
        const { data } = await classifyLov({ parentId: "", level: 5 });
        this.classifyLov = { ...this.classifyLov, ...data };
        this.expirationTime = Date.now() + 60 * 60 * 1000; // 1小时过期
        this.saveToStorage(); // 保存到 localStorage
        return data;
      } catch (error) {
        console.error("Failed to fetch classify LOV:", error);
        throw error;
      }
    },

    // 清除缓存
    clearClassifyLovCache() {
      this.classifyLov = {};
      this.expirationTime = 0;
      localStorage.removeItem(STORAGE_KEY); // 移除 localStorage 数据
    },
  },
});

// 可选：提供外部直接使用的 store 实例
export function useClassifyLovStoreWithOut() {
  return useClassifyLovStore();
}
